package com.deng.mail.authserver.mailauthserver.web;

import com.deng.mail.authserver.mailauthserver.exception.PhoneExistException;
import com.deng.mail.authserver.mailauthserver.exception.UserNameExistException;
import com.deng.mail.authserver.mailauthserver.service.IMemberService;
import com.deng.mail.authserver.mailauthserver.service.SmsService;
import com.deng.mail.authserver.mailauthserver.vo.UserRegisterVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

import static com.deng.mail.authserver.mailauthserver.service.impl.SmsServiceImpl.REDIS_SMS_PREFIX;

@Controller
@Slf4j
public class LoginController {

    @Autowired
    SmsService smsService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    IMemberService memberService;

    @GetMapping("/sendSms")
    public Object sendSms(@RequestParam("phone") String phone) {
        boolean flag = smsService.sendSms(phone);
        if (flag) {
            return "success";
        }
        return "fail";
    }

    @PostMapping("/register")
//    @ResponseBody
    public Object register(@Valid UserRegisterVo vo, BindingResult result, /*Model model*/RedirectAttributes redirectAttributes) {
        // 校验出错，转发到注册页
        Map<String, String> errorMap = new HashMap<>();
        if (result.hasErrors()) {
            errorMap = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
//            model.addAttribute("errors", errorMap);
            redirectAttributes.addFlashAttribute("errors", errorMap);
            // Request method 'POST' not supported
            // 用户注册 -> /register[port] -> forward:/reg.html转发（路径映射默认是get方式），所以不能用forward
//            return "forward:/reg.html"; 使用转发，会报post not support，因为该请求是post，路径映射需要get，所以不使用转发
//            return "reg"; // 直接请求，刷新页面会重复提交表单，也不使用
            System.out.println(errorMap);
            return "redirect:/reg.html"; // 使用重定向，会获取不到mode的数据，使用RedirectAttributes
        }

        // 注册
        // 校验验证码
        String code = redisTemplate.opsForValue().get(REDIS_SMS_PREFIX + vo.getPhone());
        if (!StringUtils.isEmpty(code)) {
            code = code.split("_")[0];
            if (StringUtils.equals(code, vo.getCode())) {
                try {
                    memberService.register(vo);
                } catch (UserNameExistException e) {
                    errorMap.put("userName", e.getMessage());
                } catch (PhoneExistException phoneExistException) {
                    errorMap.put("phone", phoneExistException.getMessage());
                }
            } else {
                errorMap.put("code", "验证码错误");
            }
        } else {
            errorMap.put("code", "验证码错误");
        }

        if (!errorMap.isEmpty()) {
            redirectAttributes.addFlashAttribute("errors", errorMap);
            return "redirect:/reg.html";
        }

        return "success";

    }

    // 被webconfig中的视图跳转替换
    /*    *//**
     * 发送一个请求直接跳转页面
     * @return
     */
    /*@GetMapping("/login.html")
    public String loginPage() {
        log.info("login.html");
        return "login";
    }

    @GetMapping("/reg.html")
    public String regPage() {
        log.info("reg.html");
        return "reg";
    }*/
}
